﻿using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.ObjectMapping;
using Abp.Runtime.Caching;
using AVIS.OutBound.Regions.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AVIS.OutBound.Regions
{
    public class RegionManager : DomainService, IRegionManager
    {
        private readonly IRegionRepository _regionRepository;
        private readonly IObjectMapper _objectMapper;
        private readonly ICacheManager _CacheManager;

        public RegionManager(IRegionRepository regionRepository,
            IObjectMapper objectMapper,
            ICacheManager CacheManager)
        {
            _regionRepository = regionRepository;
            _objectMapper = objectMapper;
            _CacheManager = CacheManager;
        }

        /// <summary>
        /// 获取指定编号的地区信息
        /// </summary>
        /// <param name="code">编号</param>
        /// <returns></returns>
        public Region GetRegion(string code)
        {
            var cacheKey = code.ToUpper();
            var cacheItems = _CacheManager.GetRegionCache().Get(cacheKey, f => GetRegionCacheItem(code));
            return _objectMapper.Map<Region>(cacheItems.FirstOrDefault());
        }

        /// <summary>
        /// 获取指定RegionCode的地区信息
        /// </summary>
        /// <param name="RegionCode"></param>
        /// <returns></returns>
        private List<RegionCacheItem> GetRegionCacheItem(string RegionCode)
        {
            var data = _regionRepository.GetRegionByCode(RegionCode);
            var region = _objectMapper.Map<RegionCacheItem>(data);
            return new List<RegionCacheItem> { region };
        }
    }
}
